<template>
  <div class="order-query-managner">

    <div class="query-from">
      <el-form>
        <el-row :gutter="24">

          <el-col :span="4">
            <el-form-item label="产品" label-width="80px">
              <el-select-v2
                  v-model="queryParam.product_id"
                  filterable
                  :options="selectProductList"
                  placeholder="请选择查询的产品"
                  style="width: 100%"
                  clearable
                  :props="{ value: 'product_id', label: 'product_name' }"
                  value-key="product_id"
              >
                <template #default="{ item }">
                  <el-tooltip
                      effect="dark"
                      :content="item.product_name"
                      placement="right"
                      :open-delay="500"
                      :hide-after="0"
                  >
                    <span class="truncate">{{ item.product_name }}</span>
                  </el-tooltip>
                </template>
              </el-select-v2>




            </el-form-item>
          </el-col>



          <el-col :span="4">
            <el-form-item label="渠道" label-width="80px">
              <el-select-v2 v-model="queryParam.channel_id" filterable disabled :options="selectChannelList"
                placeholder="请选择查询的渠道" style="width: 100%" clearable :props="{
                  value: 'channel_id',
                  label: 'channel_name'
                }" >
                <template #default="{ item }">
                  <el-tooltip
                      effect="dark"
                      :content="item.channel_name"
                      placement="right"
                      :open-delay="500"
                      :hide-after="0"
                  >
                    <span class="truncate">{{ item.channel_name }}</span>
                  </el-tooltip>
                </template>
              </el-select-v2>
            </el-form-item>
          </el-col>



          <el-col :span="4">
            <el-form-item label="客户" label-width="80px">
              <el-select-v2 v-model="queryParam.customer_id" filterable disabled :options="selectCustomerList"
                placeholder="请选择查询的客户" style="width: 100%" clearable :props="{
                  value: 'customer_id',
                  label: 'customer_shortname'
                }" >
                <template #default="{ item }">
                  <el-tooltip
                      effect="dark"
                      :content="item.customer_shortname"
                      placement="right"
                      :open-delay="500"
                      :hide-after="0"
                  >
                    <span class="truncate">{{ item.customer_shortname }}</span>
                  </el-tooltip>
                </template>
              </el-select-v2>
            </el-form-item>
          </el-col>


          <el-col :span="4">
            <el-form-item label="状态" label-width="80px">
              <el-select v-model="queryParam.order_status" filterable placeholder="请选择查询的订单状态" style="width: 100%"
                clearable>
                <el-option v-for="item in orderStatusList" :key="item.order_status" :label="item.order_statusename"
                  :value="item.order_status" />
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="4" class="textarea-wrap">
            <el-form-item label="查询单号" label-width="80px">
              <div class="textarea-floating-wrapper">
                <el-input v-model="textarea" style="width: 300px" :rows="3" type="textarea" placeholder="请输入单号(请勿输入过量单号，请先用其他条件)" @paste="handlePaste" />
              </div>
            </el-form-item>
          </el-col>

          <el-col :span="4" style="text-align: right;">
          <el-button type="text" @click="expanded = !expanded">
              {{ expanded ? '收起' : '更多条件' }}
              <el-icon :name="expanded ? 'arrow-up' : 'arrow-down'"></el-icon>
            </el-button>
          </el-col>
          
        </el-row>


        <el-row :gutter="24">
          <el-col :span="4">
            <el-form-item label="平台标签" label-width="80px">
              <el-select v-model="queryParam.upload_erp_label_sign" filterable placeholder="请选择" style="width: 100%"
                clearable>
                <el-option label="已上传" key="Y" value="Y" />
                <el-option label="未上传" key="N" value="N" />
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="4">
            <el-form-item label="是否打印" label-width="80px">
              <el-select v-model="queryParam.print_sign" filterable placeholder="请选择" style="width: 100%" clearable>
                <el-option label="已打印" key="Y" value="Y" />
                <el-option label="未打印" key="N" value="N" />
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="8">
            <div style="display: flex; align-items: center; gap: 10px">
              <!-- 时间类型选择（创建/打印） -->
              <el-select
                  v-model="queryParam.time_type"
                  filterable
                  placeholder="请选择"
                  style="width: 20%"
              >
                <el-option label="创建时间" key="create" value="create" />
                <el-option label="打印时间" key="print" value="print" />
              </el-select>

              <!-- 日期时间范围选择器 -->
              <el-form-item style="flex: 1; margin-bottom: 0">
                <el-date-picker
                    v-model="create_dateRange"
                    type="datetimerange"
                    range-separator="到"
                    start-placeholder="开始时间"
                    end-placeholder="结束时间"
                    unlink-panels
                    style="width: 80%"
                    :default-time="defaultTime"
                    :shortcuts="shortcuts"
                    :clearable="false"
                />
              </el-form-item>
            </div>
          </el-col>
        </el-row>
        <el-collapse-transition>
          <div v-show="expanded">
            <el-row :gutter="24">
              <el-col :span="4">
                <el-form-item label="COS标签" label-width="80px">
                  <el-select v-model="queryParam.push_cos_sign" filterable placeholder="请选择" style="width: 100%"
                    clearable>
                    <el-option label="已上传" key="Y" value="Y" />
                    <el-option label="未上传" key="N" value="N" />
                  </el-select>
                </el-form-item>
              </el-col>


              <el-col :span="4">
                <el-form-item label="航空主单" label-width="80px">
                  <el-input v-model="queryParam.aviation_number" placeholder="请输入" clearable></el-input>
                </el-form-item>
              </el-col>

            </el-row>
          </div>

        </el-collapse-transition>



        <el-row :gutter="24" justify="end">
          <el-col :span="4" :offset="16" style="text-align: right;">
            <el-button type="primary" @click="exportQuery" :loading="loading" :disabled="loading">导出数据</el-button>
            <el-button type="primary" @click="onSearch" :loading="loading" :disabled="loading">查询</el-button>
            <el-button @click="onReset" style="margin-left: 10px;">重置</el-button>
          </el-col>
        </el-row>
      </el-form>
    </div>


    <div class="base-tabel">
      <div class="tabel-action">
        <!-- <el-button type="primary" >添加</el-button>
            <el-button type="danger">删除</el-button> -->
        <el-button type="primary" @click="openLogsDialog()">日志</el-button>
        <el-button type="danger" @click="deleteLabel()">删除标签</el-button>
      </div>

      <div class="table-wrapper">



        <div >
          <span v-if="selectedRowsCount > 0" style="color: #409EFF;">
            ✅ 已选择 {{ selectedRowsCount }} 条记录
          </span>
          <el-table ref="tableRef" :data="tableData" style="min-width: 1280px;" max-height="550px" :stripe="true"
            :border="true" :header-cell-style="{ textAlign: 'center' }" highlight-current-row
            :row-key="row => row.order_id" @selection-change="handleSelectionChange"
             v-loading="loading"
            :element-loading-svg="svg"
            class="custom-loading-svg"
            >
            <el-table-column type="selection" min-width="40" align="center" reserve-selection />
            <el-table-column fixed prop="order_statusename" label="订单状态" min-width="100" align="center" />
            <el-table-column fixed prop="order_customerinvoicecode" label="订单号" min-width="150" align="center" />
            <el-table-column prop="order_serveinvoicecode" label="转单号" min-width="150" align="center" />
            <!-- <el-table-column prop="customer_shortname" label="客户" min-width="150"  align="center"/> -->
            <el-table-column prop="product_name" label="产品" min-width="150" align="center" />
            <!-- <el-table-column prop="channel_name" label="渠道" min-width="150"  align="center"/> -->
            <el-table-column prop="product_transfer_name" label="中转产品" min-width="150" align="center" />
            <el-table-column prop="upload_erp_label_sign" label="平台标签" min-width="80" align="center">
              <template #default="{ row }">
                <el-checkbox v-model="row.upload_erp_label_sign" :true-value="'Y'" class="custom-readonly-checkbox" />
              </template>
            </el-table-column>
            <el-table-column prop="upload_erp_label_sign" label="COS标签" min-width="80" align="center">
              <template #default="{ row }">
                <el-checkbox v-model="row.push_cos_sign" :true-value="'Y'" class="custom-readonly-checkbox" />
                    <el-tooltip content="预览标签" placement="top">
                        <el-button
                          link
                          type="primary"
                          size="large"
                          @click="handleLabelPreview(row.order_id)"
                          style="margin-left: 15px"
                        >
                          <el-icon><View /></el-icon>
                        </el-button>
                      </el-tooltip>
              </template>
            </el-table-column>
            <el-table-column prop="print_web_user_name" label="打印人" align="center" min-width="100"></el-table-column>
            <el-table-column prop="print_web_time" label="打印时间" min-width="200" align="center"></el-table-column>

            <!-- ✅ 合并三列为一列 -->
            <!-- <el-table-column label="产品 / 渠道 / 中转产品" width="240" align="center">
                    <template #default="{ row }">
                        <template v-if="row && (row.product_id || row.channel_id || row.product_transfer)">
                    <div v-if="row.product_id">产品：{{ row.product_id }}</div>
                    <div v-if="row.channel_id">渠道：{{ row.channel_id }}</div>
                    <div v-if="row.product_transfer">中转产品：{{ row.product_transfer }}</div>
                        </template>
                    </template>
                </el-table-column> -->

            <el-table-column prop="order_createdate" label="创建时间" width="200" align="center" />
          </el-table>


          <div class="demo-pagination-block">
            <el-pagination v-model:current-page="queryParam.pageNumber" v-model:page-size="queryParam.pageSize"
              :page-sizes="[20, 50, 100]" :background="true" layout="total, sizes, prev, pager, next, jumper"
              :total="currentTotalData" @size-change="handleSizeChange" @current-change="handleCurrentChange" />
          </div>

        </div>

      </div>

    </div>

    <BusinessLogDialog ref="logDialog" v-model="showLogDialog"/>

  </div>

</template>

<script setup name="orderQuery">

//一些导入
import {postDownloadFile, previewLabel, queryOrderInfo,deleteLabelOrder} from '@/api'
import { onMounted, onUnmounted, ref, watch, nextTick, computed } from 'vue'
import { formatDate, getRecentNDaysRange, parseDate } from '@/utils/timeUtils'
import { useDictStore } from '@/store/dictStore'
import { ElMessage ,ElMessageBox} from 'element-plus'
import { useRoute,useRouter } from 'vue-router'
import { useUserStore } from '@/store/user'
import BusinessLogDialog from "@/views/log/BusinessLogDialog.vue";

const route = useRoute()

const router = useRouter()
//加载字典
const dictStore = useDictStore()

const userStore = useUserStore()



//============================================================================================================================
//定义一些参数

const logDialog = ref()

const showLogDialog = ref(false)

// 全部勾选的数据
let selectedRows = ref(new Map())
//定义产品下拉框
let selectProductList = ref([])
//渠道下拉框
let selectChannelList = ref([])
//客户下拉框
let selectCustomerList = ref([])
//查询总数
let currentTotalData = ref(0)
//表格的引用
let tableRef = ref(null)
let orderStatusList = ref([])
let textarea = ref('')
let expanded = ref(false)
//定义查询Dto
let queryParam = ref({
  pageNumber: 1,
  pageSize: 20,
  start_time: '',
  end_time: '',
  upload_erp_label_sign: '',
  queryOrderCodes: [],
  product_id: '',
  channel_id: '',
  customer_id: '',
  order_status: '',
  push_cos_sign: '',
  print_type:null,
  filter_print_order:true,
  aviation_number: '',
  label_config_id: '',
  time_type:'create'
})
const svg = `
        <path class="path" d="
          M 30 15
          L 28 17
          M 25.61 25.61
          A 15 15, 0, 0, 1, 15 30
          A 15 15, 0, 1, 1, 27.99 7.5
          L 15 15
        " style="stroke-width: 4px; fill: rgba(0, 0, 0, 0)"/>
      `

//定义返回表格的数据
let tableData = ref([])

let defaultTime = [
  new Date(new Date().setHours(0, 0, 0, 0)),       // 今天0点0分0秒
  new Date(new Date().setHours(23, 59, 59, 999))  // 今天23点59分59秒999毫秒
]


const createRangeShortcut = (text, days) => ({
  text,
  value: () => {
    const end = setEndOfDay(new Date())
    const start = setStartOfDay(new Date())
    start.setDate(end.getDate() - days)
    return [start, end]
  }
})

//快捷选择时间
let shortcuts = [
  createRangeShortcut('1周前', 7),
  createRangeShortcut('2周前', 14),
  createRangeShortcut('3周前', 21),
  createRangeShortcut('1个月前', 30),
  createRangeShortcut('2个月前', 60),
  createRangeShortcut('3个月前', 90),
  createRangeShortcut('半年前', 180),
]


// 绑定给 <el-date-picker> 的值，必须是 Date 对象数组
let create_dateRange = ref([])

let print_dateRange = ref([])

let loading = ref(false)


//==============================================================================================================================================

//定义一些方法

//根据条件查询订单
async function fetchData() {
  // console.log(queryParam.value)
  try{
    loading.value = true
    await queryOrderInfo(queryParam.value).then(resp => {
      tableData.value = resp.list;
      currentTotalData.value = resp.total;
    });
  }finally{
  loading.value = false
  }

}

//分页查询
const handleSizeChange = (num) => {
  queryParam.value.pageSize = num;
  queryParam.value.pageNumber = 1; // 通常重置页码为1
  fetchData();
};

const handleCurrentChange = (num) => {
  queryParam.value.pageNumber = num;
  fetchData();
};

const initDateRange = () => {
  let [startStr, endStr] = getRecentNDaysRange(1)
  create_dateRange.value = [parseDate(startStr), parseDate(endStr)]
}

//重置
const onReset = () => {

  router.replace({
    path: route.path,
    query: {}  // 清空所有 query 参数
  })
  textarea.value = ''
  let filterPrintOrder = queryParam.value.filter_print_order;
  Object.keys(queryParam.value).forEach(key => {
    // 如果是数组，重置为空数组，否则重置为空字符串或null
    if (Array.isArray(queryParam.value[key])) {
      queryParam.value[key] = []
    } else if (typeof queryParam.value[key] === 'object') {
      queryParam.value[key] = null
    } else {
      queryParam.value[key] = ''
    }
  })
  queryParam.value.filter_print_order = filterPrintOrder
  queryParam.value.time_type = 'create'

  queryParam.value.pageNumber = 1
  queryParam.value.pageSize = 20

  //重新初始化
  initDateRange()

  clearSelection()
}




const exportQuery = async () =>{
  if (!create_dateRange.value || create_dateRange.value.length !== 2) {
    ElMessage.warning('请选择完整的时间范围')
    return
  }

  let [startDate, endDate] = create_dateRange.value


  // 标准化时间
  startDate = setStartOfDay(startDate)
  endDate = setEndOfDay(endDate)



  let now = new Date()
  let halfYearAgo = new Date()
  halfYearAgo.setMonth(now.getMonth() - 6)
  let halfYearAgoStart = setStartOfDay(halfYearAgo)
  let nowEnd = setEndOfDay(now)

  if (startDate < halfYearAgoStart) {
    ElMessage.warning('开始时间不能早于半年前')
    return
  }

  if (endDate > nowEnd) {
    ElMessage.warning('结束时间不能晚于当前时间')
    return
  }

  try {
    loading.value = true
    await postDownloadFile("/order/exportQuery",queryParam.value)
  } catch (err) {
    ElMessage.warning('导出异常', err)
  } finally {
    loading.value = false
  }
}




//查询方法
const onSearch = async () => {
  if (!create_dateRange.value || create_dateRange.value.length !== 2) {
    ElMessage.warning('请选择完整的时间范围')
    return
  }

  let [startDate, endDate] = create_dateRange.value

  // 标准化时间
  startDate = setStartOfDay(startDate)
  endDate = setEndOfDay(endDate)

  let now = new Date()
  let halfYearAgo = new Date()
  halfYearAgo.setMonth(now.getMonth() - 6)
  let halfYearAgoStart = setStartOfDay(halfYearAgo)
  let nowEnd = setEndOfDay(now)

  if (startDate < halfYearAgoStart) {
    ElMessage.warning('开始时间不能早于半年前')
    return
  }

  if (endDate > nowEnd) {
    ElMessage.warning('结束时间不能晚于当前时间')
    return
  }

  if (!queryParam.value.print_type && queryParam.value.print_sign === "N" )
  {
    if (queryParam.value.time_type === "print") {
      ElMessage.warning('时间类型不能是打印时间')
      return
    }
  }

  queryParam.value.queryOrderCodes = textarea.value
    .split('\n')
    .map(code => code.trim())
    .filter(Boolean)

  //重新指定页数
  queryParam.value.pageNumber = 1;


  expanded.value = false
  try {
    
      fetchData()
      clearSelection()
  } catch (err) {
    ElMessage.warning('查询异常', err)
  } finally {
    
  }


}

const setStartOfDay = (date) => {
  let d = new Date(date)
  d.setHours(0, 0, 0, 0)
  return d
}

const setEndOfDay = (date) => {
  let d = new Date(date)
  d.setHours(23, 59, 59, 999)
  return d
}



//勾选触发
const handleSelectionChange = (selection) => {
  // 更新 map：把当前页选中的行加进来

  selection.forEach(row => {
    selectedRows.value.set(row.order_id, row)
  })

  tableData.value.forEach(row => {
    if (selectedRows.value.has(row.order_id)) {
      if (!selection.some(item => item.order_id === row.order_id)) {
        selectedRows.value.delete(row.order_id)
      }
    }
  })
  console.log(selectedRows.value)
}


const clearSelection = () => {
  selectedRows.value.clear()
  tableRef.value?.clearSelection()
}

async function initPageData() {
  await initDateRange()
  const [product, channel, customer, orderStatus] = await Promise.all([
    dictStore.loadDict('product'),
    dictStore.loadDict('channel'),
    dictStore.loadDict('customer'),
    dictStore.loadDict('orderStatus'),
  ])

  selectProductList.value = product

  selectChannelList.value = channel
  selectCustomerList.value = customer
  orderStatusList.value = orderStatus

  //设置当前登录人为打印人 

  // requestIdleCallback(async () => {
  //   dictStore.loadDict('product').then(v=> selectProductList.value = v)
  // })

  // requestIdleCallback(async () => {
  //   selectChannelList.value = await dictStore.loadDict('channel')
  // })

  // requestIdleCallback(async () => {
  //   selectCustomerList.value = await dictStore.loadDict('customer')
  // })

  // fireAndForget(async () => {
  //   orderStatusList.value = await dictStore.loadDict('orderStatus')
  // })
}

const handleLabelPreview = (id)=>{
    try {
    previewLabel(id).then(data=>{
      console.log(data)
        if(data.code === 200){
          if(data.data){
            webUrl2BlobUrl(data.data).then(data=>{
            console.log(data)
            window.open(data, '_blank')
            setTimeout(() => {
              URL.revokeObjectURL(data)
            }, 60 * 1000)
            })

          }else{
            ElMessage.error("未找到标签")
          }
        }
    })
  } catch (err) {
    ElMessage.error(`预览失败：${err.message || err}`)
  }
}

const webUrl2BlobUrl = async (webUrl, options = {}) =>{
      const { fetchHeaders = {}, fileType = '' } = options;

      try {
        debugger
        const response = await fetch(webUrl, {
          mode: 'cors',
          headers: fetchHeaders,
        });

        if (!response.ok) {
          // console.error(`Fetch 失败: HTTP ${response.status}`);
          return null;
        }

        const blob = await response.blob();

        // 推断或指定 MIME 类型
        const blobType = blob.type || 'application/octet-stream';

        const finalBlob = new Blob([blob], { type: blobType });
        const blobUrl = URL.createObjectURL(finalBlob)

        return blobUrl;
      } catch (e) {
        console.error('webUrl2BlobUrl 异常:', e);
        return null;
      }

    }

const handlePaste = (e) => {

  //elementui的粘贴在单号多的时候会造成卡顿 原因是一直触发了属性刷新
  const pasted = e.clipboardData?.getData('text') || ''
  const lines = pasted.split(/\r?\n/)

  if (lines.length > 5000) {
    e.preventDefault() // 阻止默认粘贴行为
    textarea.value = lines.slice(0, 5000).join('\n') // 手动赋值
  }
}


const openLogsDialog = ()=>{
  if (selectedRows.value.size === 0) {
    ElMessage.warning('请选择要操作的行')
    return
  }
  if (selectedRows.value.size > 1) {
    ElMessage.warning('请勿操作多行')
    return
  }
  let keyset = selectedRows.value.keys()
  // 调用子组件方法
  logDialog.value.open('ORDER', Array.from(selectedRows.value.keys())[0])
}

const deleteLabel = ()=>{
  if (selectedRows.value.size === 0) {
    ElMessage.warning('请选择要操作的行')
    return
  }

  let keyset = selectedRows.value.keys()

  ElMessageBox.confirm(
      '确定要删除选中的记录吗？',  // 提示内容
      '删除确认',                 // 弹窗标题
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
  ).then(() => {
    // 用户点击确定
    deleteLabelOrder(Array.from(keyset)).then((data) => {
      if (data && data.code === 200) {
        ElMessage.success('删除成功')

        onSearch()
      } else {
        ElMessage.error(data.message || '删除失败')
      }
    })
  }).catch(() => {
    // 用户点击取消

  })
}

//==============================================================================================================================================

//定义一些计算属性 或者  监视属性

// 监听 dateRange 的变化，更新 queryParam
watch(create_dateRange, (newVal) => {
  if (newVal.length === 2) {
    queryParam.value.start_time = formatDate(newVal[0])
    queryParam.value.end_time = formatDate(newVal[1])
  } else {
    queryParam.value.start_time = ''
    queryParam.value.end_time = ''
  }
}, { immediate: true })



//计算属性
let selectedRowsCount = computed(() => selectedRows.value.size)


//==============================================================================================================================================
//定义钩子
onMounted(async () => {
  await initPageData()
  const hasQuery = Object.keys(route.query).length > 0
  if (hasQuery) {
    // 等待 options 加载后再赋值


    if (route.query.product_id) {
      queryParam.value.product_id = Number(route.query.product_id)
    }

    if (route.query.push_cos_sign) {
      queryParam.value.push_cos_sign = route.query.push_cos_sign
    }

    if(route.query.print_type){
      queryParam.value.print_type = Number(route.query.print_type)
    }

    if (route.query.channel_id){
      queryParam.value.channel_id = Number(route.query.channel_id)
    }

    if (route.query.customer_id){
      queryParam.value.customer_id = Number(route.query.customer_id)
    }

    if (route.query.label_config_id){
      queryParam.value.label_config_id = Number(route.query.label_config_id)
    }

    //这个必定有在这里判断下
    if (route.query.label_push_start_date) {
      const start = parseDate(route.query.label_push_start_date)
      const end = create_dateRange.value?.[1] || null
      create_dateRange.value = end ? [start, end] : [start]
      queryParam.value.filter_print_order = false
    }

    nextTick(() => {
      onSearch()
    })
  }
})

//==============================================================================================================================================



</script>

<style lang="scss" scoped>
.table-wrapper {
  width: 100%;
  overflow-x: auto;
}

.query-from {
  background-color: #ffffff;
  padding: 20px 20px 0;
  border-radius: 5px;
  padding-bottom: 10px;
  /* 最底部间距 */
}

.base-tabel {
  border-radius: 5px;
  background: #ffffff;
  margin-top: 20px;
  margin-bottom: 20px;

  .tabel-action {
    border-radius: 5px 5px 0px 0px;
    background: #ffffff;
    padding: 20px;
    border-bottom: 1px solid #ece8e8
  }

  .pagination {
    text-align: center;
    padding: 20px;
  }
}

.demo-pagination-block {
  display: flex;
  justify-content: center;
  padding: 20px 0;
}

.custom-readonly-checkbox {
  pointer-events: none;
  /* 禁止点击 */
}

.textarea-wrap {
  position: relative;
}

.textarea-floating-wrapper {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;

}
.truncate {
  display: inline-block;
  max-width: 100%;
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
}

</style>